<template>
  <div class="page-concent">
    <!-- 页面面包屑 -->
    <a-breadcrumb>
      <a-breadcrumb-item>文章管理</a-breadcrumb-item>
      <a-breadcrumb-item style="cursor: default" @click="router.push({ name: 'BackendBlogList' })"
        >文章列表</a-breadcrumb-item
      >
      <a-breadcrumb-item>文章创建</a-breadcrumb-item>
    </a-breadcrumb>
    <!-- 提交表单 -->
    <div>
      <!-- 提交表单 -->
      <a-form :model="form" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item field="title" label="标题" label-col-flex="200px">
              <a-input v-model="form.title" placeholder="请输入文章标题" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-form-item field="content" label="内容" label-col-flex="80px">
            <MdEditor v-model="form.content" @onSave="onSaveHandler" />
          </a-form-item>
        </a-row>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { BLOG_CREATE, BLOG_GET, BLOG_UPDATE } from '@/api/blog'
import { Message } from '@arco-design/web-vue'

const router = useRouter()
const route = useRoute()

// 需要条件的表单数据
const form = reactive({
  title: '',
  content: ''
})

// onSave事件: v value, h 渲染后的html
const onSaveHandler = async () => {
  const id = route.query.id
  console.log(id)
  if (id) {
    // 执行更新
    try {
      const resp = await BLOG_UPDATE(id, form)
      Message.success(`文章[${resp.title}]更新成功`)
      // 使用返回的数据修改当前页面数据, 绑定到From上
      form.title = resp.title
      form.content = resp.content
    } catch (error) {
      Message.error(`更新失败: ${error}`)
    }
  } else {
    // 执行创建
    try {
      const resp = await BLOG_CREATE(form)
      router.push({ name: 'BackendBlogList' })
      Message.success(`文章[${resp.title}]创建成功`)
    } catch (error) {
      Message.error(`保存失败: ${error}`)
    }
  }
}

onMounted(async () => {
  const id = route.query.id

  if (id) {
    // 如果id存在 就 查询博客数据
    try {
      const resp = await BLOG_GET(route.query.id)
      console.log(resp)
      // 绑定到From上
      form.title = resp.title
      form.content = resp.content
    } catch (error) {
      Message.error(`查询博客失败: ${error}`)
    }
  }
})
</script>

<style lang="scss" scoped></style>
